package com.heisen.security.configure;

import com.heisen.security.handler.ApiResourceOpenHander;
import com.heisen.security.handler.XmAccessDeniedHandler;
import com.heisen.security.handler.XmAuthExceptionEntryPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @author sen
 * @description
 * @date 2023/12/29 16:57
 */
@Slf4j
@Configuration
@EnableResourceServer //是一个资源服务器
public class ServerSystemResourceServerConfigure extends ResourceServerConfigurerAdapter {

    @Autowired
    private XmAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private XmAuthExceptionEntryPoint exceptionEntryPoint;

    @Autowired
    ApiResourceOpenHander apiResourceOpenHander;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .requestMatchers().antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers(apiResourceOpenHander.handle()).permitAll() // 放行路径
                .antMatchers("/**").authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(exceptionEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
    }

    /**
     *  加密方式
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();  //BCryptPasswordEncoder的特点就是，对于一个相同的密码，每次加密出来的加密串都不同：
    }
}
